/**
 * 在该文件中定义全局过滤器，在需要用到过滤器的页面对应的 main.js 中引入， 并注册全局过滤器
 */
import el from "element-ui/src/locale/lang/el"
import store from "@/store"

const dfilters = {
	/**
	 * 大数字转换 将数字分段显示，每三位用逗号隔开
	 */
	formatNumber(value) {
		return value.replace(/(?=(?!\b)(\d{3})+$)/g, ",")
	},
	/**
	 * 格式化金额
	 * @param value
	 * @returns {string|boolean}
	 */
	formatMoney(value){
		if(!value) {
			return "-"
		}
		//强制保留两位小数
		let f = parseFloat(value);
		if (isNaN(f)) return false;
		f = Math.round(value * 100) / 100;
		let s = f.toString();
		let rs = s.indexOf('.');
		if (rs < 0) {
			rs = s.length;
			s += '.';
		}
		while (s.length < (rs + 1) + 2) {
			s += '0';
		}
		//每三位用一个逗号隔开
		let leftNum=s.split(".")[0];
		let rightNum="."+s.split(".")[1];
		let result;
		//定义数组记录截取后的价格
		let resultArray=new Array();
		if(leftNum.length>3){
			let i=true;
			while (i){
				resultArray.push(leftNum.slice(-3));
				leftNum=leftNum.slice(0,leftNum.length-3);
				if(leftNum.length<4){
					i=false;
				}
			}
			//由于从后向前截取，所以从最后一个开始遍历并存到一个新的数组，顺序调换
			let sortArray=new Array();
			for(let i=resultArray.length-1;i>=0;i--){
				sortArray.push(resultArray[i]);
			}
			result=leftNum+","+sortArray.join(",")+rightNum;
		}else {
			result=s;
		}
		return result;
	},
	/**
	 * 格式化客户简称
	 */
	customerShortName: function (val) {
		if (!val) {
			return '';
		}
		if (val == '无') {
			return '无';
		}
		let customerList = JSON.parse(window.sessionStorage.getItem("customerData"))
		let array = val.split(",")
		let result = ""
		array.forEach(item => {
			let isFind = false
			for (let i in customerList) {
				if (customerList[i].customerName == item) {
					if (item == '无') {
						result += "无,"
					}else{
						result += customerList[i].customerShortName+","
					}
					isFind = true
					break;
				}
			}
			if (!isFind) {
				result += item+","
			}
		})
		return result.substring(0,result.length-1)
	},
	/**
	 * 检测数据是否一致
	 */
	compareData: function (oldVal, newVal) {
		// console.log("old--->", JSON.stringify(oldVal))
		// console.log("new--->", JSON.stringify(newVal), JSON.stringify(oldVal) == JSON.stringify(newVal))
		// console.log("bool--->", JSON.stringify(oldVal) == JSON.stringify(newVal))
		if (JSON.stringify(oldVal) == JSON.stringify(newVal)) {
			return true
		} else {
			return false
		}
	},
	/**
	 * 空值处理
	 */
	valNullHandler: function (value, placeholder) {
		if (value == null || value == undefined || (value + "").length < 1) return placeholder ? placeholder : ""
		else return value
	},
	/**
	 * 数字空值处理
	 */
	valNumberNullHandler: function (value, placeholder) {
		if (value == null || value == undefined || (value + "").length < 1 || isNaN(value)) return placeholder ? placeholder : ""
		else return value
	},
	/**
	 * 小数点后指定位数
	 *
	 * @param value
	 * @param decimal
	 */
	showFloat: function (value, decimal) {
		if (value == null || (value + "").length < 1 || isNaN(value)) return ""
		if (decimal == null || (value + "").length < 1 || isNaN(value)) decimal = 2
		return Math.round(value * Math.pow(10, decimal)) / Math.pow(10, decimal)
	},
	/**
	 * json数组中的某个指定的字段，按一定格式拼接成字符串
	 *
	 * @param value 原始值JsonArray格式
	 * @param fieldNameArr JSONArray中某几个对象的某个key
	 * @param separator 分隔符（list中每个对象之间的分割符）
	 */
	jsonArrayJoin: function (value, fieldNameArr, separator) {
		if (value == null || value == undefined) return ""

		if (!(typeof value == "string")) {
			value = JSON.stringify(value)
		}
		if ((value + "").length < 1 || !isJSON(value)) return ""

		let objArr = JSON.parse(value)
		let val = ""
		for (let index in objArr) {
			if (index == objArr.length - 1) {
				if (fieldNameArr != null && fieldNameArr.length > 0) {
					let objVal = ""
					for (let filed_index in fieldNameArr) {
						objVal += objArr[index][fieldNameArr[filed_index]] ? objArr[index][fieldNameArr[filed_index]] : ""
					}

					val += objVal
				} else {
					val += objArr[index] ? objArr[index] : ""
				}
			} else {
				if (fieldNameArr != null && fieldNameArr.length > 0) {
					let objVal = ""
					for (let filed_index in fieldNameArr) {
						objVal += objArr[index][fieldNameArr[filed_index]] ? objArr[index][fieldNameArr[filed_index]] : ""
					}

					val += objVal + separator
				} else {
					val += (objArr[index] ? objArr[index] : "") + separator
				}
			}
		}
		return val
	},
	FilterByName(data, Name) {
		//data是json对象，Name是根据什么字段去重
		var map = {},
			dest = []
		for (var i = 0; i < data.length; i++) {
			var ai = data[i]
			if (i == 0) {
				dest.push(ai)
			} else {
				var filterData = dest.filter(function (e) {
					return e[Name] == ai[Name]
				})
				if (filterData.length == 0) {
					dest.push(ai)
				}
			}
		}
		return dest
	},
	/**
	 * 获取显示的信息
	 *
	 * @param value 源数据
	 * @param showFileName 需要展示的字段
	 * @param checkFieldName 需要校验的字段
	 * @param dataList 列表数据
	 */
	getNameFromList(value, showFileName, checkFieldName, dataList) {
		if (value == null || (value + "").length < 1 || dataList == null || dataList.length == 0) return ""

		let name = ""
		dataList.forEach(item => {
			if (value === item[checkFieldName]) {
				name = item[showFileName]
				return
			}
		})
		return name
	},
	/**
	 * 获取显示的信息
	 * （求和后显示）
	 *
	 * @param valueArr 需要统计的条件（当校验字段的值为？时，需要累加）
	 * @param sumField 求和的字段
	 * @param sumFieldType 字段的类型 例如 int float
	 * @param checkFieldName 校验字段
	 * @param dataList 列表数据
	 */
	getTotalFromList(valueArr, sumField, sumFieldType, checkFieldName, dataList) {
		if (dataList == null || dataList.length == 0) return "0"

		let sunVal = 0
		dataList.forEach(item => {
			let tempVal = 0
			if (sumFieldType == "int") {
				tempVal = parseInt(item[sumField])
			} else if (sumFieldType == "float") {
				tempVal = parseFloat(item[sumField])
			}

			if (valueArr != null && valueArr.length > 0 && valueArr.indexOf(item[checkFieldName]) > -1) {
				sunVal += tempVal
			} else if (valueArr == null || valueArr.length == 0) {
				sunVal += tempVal
			}
		})

		return sunVal
	},
	/**
	 * 连接websokcet的接口信息
	 *
	 * @param URL 链接的websocket地址
	 *
	 */
	connectWebSocket(URL) {
		var token = window.sessionStorage.getItem("token")
		var ws = new WebSocket(`${URL}?token=${encodeURIComponent(token)}`)

		ws.onopen = function (evt) {
			console.log("Connection open ...")
			// ws.send(token);
			store.commit("updatewsobj", ws)
			// var obj = {
			// 	action: "login",
			// 	token: token,
			// }
			// ws.send(JSON.stringify(obj))
		}

		ws.onmessage = function (evt) {
			// alert(evt.data)
			//   store.commit("updatemessage","1");
			var getData = JSON.parse(evt.data)
			if (getData.msgType == "01") {
				var messageObj = {
					messageData: new Date().getTime(),
					messageContext: getData,
				}
				store.commit("updateWebSocket", messageObj)
			} else {
				var messageObj = {
					messageData: new Date().getTime(),
					messageContext: { msgType: "02", content: getData.content, unReadNum: getData.unReadNum ? getData.unReadNum : "" },
				}
				store.commit("updateWebSocket", messageObj)
			}
			if (getData.id) {
				getData.lastSendTime = new Date().getTime()
				store.commit("sotreLastedMsg", getData)
			}
			console.log("Received Message: ", evt.data)
			// ws.close();
		}

		ws.onclose = function (evt) {
			console.log("Connection closed.")
		}
		ws.onerror = function () {
			console.log("Connection error")
		}
	},
	// 获取当前日期
	formatterDateTime() {
		var date = new Date()
		var month = date.getMonth() + 1
		var datetime =
			date.getFullYear() +
			"" + // "年"
			(month >= 10 ? month : "0" + month) +
			"" + // "月"
			(date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) +
			"" +
			(date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) +
			"" +
			(date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
			"" +
			(date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds())
		return datetime
	},
	getWorkTimeByline() {
		var now = new Date()
		var year = now.getFullYear()
		var month = now.getMonth() + 1
		month = month < 10 ? "0" + month : month
		var day = now.getDate()
		day = day < 10 ? "0" + day : day
		var hour = now.getHours()
		var min = now.getMinutes()
		min = min < 10 ? "0" + min : min
		var sec = now.getSeconds()
		sec = sec < 10 ? "0" + sec : sec
		return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec
	},
	getProcessingDate(dateValue, dateType, styleType = "-") {
		// console.log('dateValue',dateValue)
		if (!dateValue) {
			return ""
		}
		var date = ""
		var dateObj = new Date(dateValue)
		var year = dateObj.getFullYear() + styleType //得到年份
		var month = dateObj.getMonth() + 1 //得到月份
		month = (month < 10 ? "0" + month : month) + styleType
		var days = dateObj.getDate() //得到日期
		days = days < 10 ? "0" + days : days
		var Hours = dateObj.getHours() //小时
		Hours = Hours < 10 ? "0" + Hours : Hours

		var min = dateObj.getMinutes() //分钟
		min = min < 10 ? "0" + min : min

		var sec = dateObj.getSeconds() //秒
		sec = sec < 10 ? "0" + sec : sec

		switch (dateType) {
			case "0": //展示年月日时分秒
				date = year + month + days + " " + Hours + ":" + min + ":" + sec
				break
			case "1": //展示月日时分秒
				month + days + " " + Hours + ":" + min + ":" + sec
				break
			case "2": // 展示月日时分
				date = month + days + " " + Hours + ":" + min
				break
			case "3": // 展示年月日
				date = year + month + days
				break
			case "4": // 展示年月日 时
				date = year + month + days + " " + Hours
				break
			case "5": // 展示年月
				date = year + month
				break
			default:
				date = year + month + days + " " + Hours + ":" + min + ":" + sec
				break
		}
		return date
	},
	/**
	 * @Author: zhangyongbing
	 * @description:
	 * @param {*}
	 * @return {*}
	 */
	getToFixed(num, s) {
		// num 表示需要四舍五入的小数
		// s 表示需要保留的几位小数
		num = num ? num : 0
		var times = Math.pow(10, s)
		var des = num * times + 0.5
		des = parseInt(des, 10) / times
		return des + ""
	},
	/**
	 * @Author: zhangyongbing
	 * @description:  浮点数相乘解决 精确度问题
	 * @param {*}
	 * @return {*}
	 */
	getTwoFloat(floatOne, floatTwo) {
		let m1 = 0
		let m2 = 0
		floatOne = (floatOne ? floatOne : 0) + ""
		floatTwo = (floatTwo ? floatTwo : 0) + ""
		if (floatOne.indexOf(".") > 0) {
			if (floatOne.split(".").length > 1) {
				m1 = floatOne.split(".")[1].length
			}
			floatOne = floatOne * Math.pow(10, m1)
		}
		if (floatTwo.indexOf(".") > 0) {
			if (floatTwo.split(".").length > 1) {
				m2 = floatTwo.split(".")[1].length
			}
			floatTwo = floatTwo * Math.pow(10, m2)
		}
		return (floatOne * floatTwo) / Math.pow(10, m1 + m2)
	}
}
export default dfilters

/**
 * 判断是否是JSON
 *
 * @param str
 * @returns {boolean}
 */
function isJSON(str) {
	if (typeof str == "string") {
		try {
			let obj = JSON.parse(str)
			if (typeof obj == "object" && obj) {
				return true
			} else {
				return false
			}
		} catch (e) {
			return false
		}
	}
}

Date.prototype.Format = function (fmt) {
	let o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		S: this.getMilliseconds(), //毫秒
	}
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length))
	for (let k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length))
	return fmt
}
